<?php

namespace addons\cms\controller\api;

use addons\cms\library\IntCode;
use addons\cms\model\ArchivesInteraction;
use addons\cms\model\Collection as CollectionModel;
use addons\cms\model\Modelx;
use addons\cms\model\ScoreLog;
use app\admin\model\cms\ActivitySign;
use think\Db;
use think\Exception;

/**
 * 会员收藏
 */
class Collection extends Base
{
    protected $layout = 'default';
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    /**
     * 我的收藏
     */
    public function index()
    {
        $collection = new CollectionModel;
        $type = $this->request->param('type');
        $q = $this->request->param('q');
        $config = ['query' => []];

        // 指定模型
        if ($type) {
            $model = Modelx::get($type);
            if ($model) {
                $collection->where('type', $type);
                $config['query']['type'] = $type;
            }
        }
        // 搜索关键字
        if ($q) {
            $collection->where('title|keywords|description', 'like', '%' . $q . '%');
            $config['query']['q'] = $q;
        }

//        $config = get_addon_config('cms');
        $user_id = $this->auth->id;
        $collectionList = $collection->where('user_id', $user_id)
            ->where('type',$type)
            ->order('id', 'desc')
            ->field('id,type,aid,createtime')
            ->paginate(10);

        $new_data = [];
        $lang = getHeaderLang();
        foreach ($collectionList as $index => $item) {
            if ($item['type'] == 'activity') {
                $item->info = \addons\cms\model\Activity::where('status', 'normal')
                    ->where('id',$item->aid)
                    ->field('updatetime,deletetime',true)
                    ->find();

                if ($lang != getDefaultLang()) {
                    $item->info->title = $item->info['title_'.$lang];
                }
                if (!$item->info){
                    continue;
                }
                $is_like = $is_collection = 0;
                if ($this->auth->id){
                    if (ArchivesInteraction::where(['user_id'=>$this->auth->id,'aid'=>$item->aid,'type' => 'activity'])->find()){
                        $is_like = 1;
                    }
                    if(\addons\cms\model\Collection::where(['user_id' => $this->auth->id,'aid' => $item->aid,'type' => 'activity'])->find()){
                        $is_collection = 1;
                    }
                }
                $sign = ActivitySign::where(['user_id'=> $this->auth->id,'activity_id'=>$item->aid])->find();
                $item->info->is_sign = $sign ? 1 : 0;
                $item->info->sign_num = ActivitySign::where('activity_id',$item->aid)->count();
                $item->info->sign_remaining = $item->info->attend_num - $item->info->sign_num;
                $item->info->is_like = $is_like;
                $item->info->is_collection = $is_collection;
            }else{
                $info = \addons\cms\model\Archives::where('status', 'normal')
                    ->where('id',$item->aid)
                    ->field('id,channel_id,user_id,title,description,description_zh_cn,description_en,title_zh_cn,title_en,image,createtime,views,likes,comments,dislikes,author,author_zh_cn,author_en')
                    ->find();
                if ($lang != getDefaultLang()) {
                    $info->title = $info['title_'.$lang];
                    $info->author = $info['author_'.$lang];
                    $info->description = $info['description_'.$lang];
                }
                if (!$info){
                    continue;
                }
                $is_like = $is_collection = 0;
                if ($this->auth->id){
                    if (ArchivesInteraction::where(['user_id'=>$this->auth->id,'aid'=>$item->aid,'type' => 'archives'])->find()){
                        $is_like = 1;
                    }
                    if(\addons\cms\model\Collection::where(['user_id' => $this->auth->id,'aid' => $item->aid,'type' => 'archives'])->find()){
                        $is_collection = 1;
                    }
                }
                $info['is_like'] = $is_like;
                $info['is_collection'] = $is_collection;
                $item->info = $info;
//                $item->info->is_like = $is_like;
//                $item->info->is_collection = $is_collection;
            }
            if (!$item->info) {
                unset($collectionList[$index]);
            }
            $new_data[] = $item->info;

        }
        $collectionList = $collectionList->toArray();
        $collectionList['data'] = $new_data;
        $this->success('获取成功', $collectionList);
//
//        $this->success('获取成功', [
//            'collectionList' => $collectionList,
//            'model'          => $model
//        ]);
    }

    /**
     * 添加收藏
     */
    public function collection()
    {
        $type = $this->request->post("type");
        if (!in_array($type, ['archives', 'page', 'special', 'diyform','activity'])) {
            $this->error("The parameter is incorrect");
        }
        if ($type == 'archives') {
            //检测ID是否加密
            $this->hashids('aid');
        }
        $aid = $this->request->post("aid/d");
        $model = call_user_func_array(['\\addons\\cms\\model\\' . ucfirst($type), "get"], [$aid]);

        if (!$model) {
            $this->error("The specified data was not found");
        }
        Db::startTrans();
        try {
            $collection = CollectionModel::lock(true)->where(['type' => $type, 'aid' => $aid, 'user_id' => $this->auth->id])->find();

            if ($collection) {
                $collection->delete();
                $model->setDec('collection', 1);
                Db::commit();
                $this->success("The operation was successful");
//                throw new \think\Exception("请勿重复收藏");
            }
            $title = $model->title;
            $url = $model->fullurl ?? '';
            $image = $model->image;
            $data = [
                'user_id' => $this->auth->id,
                'type'    => $type,
                'aid'     => $aid,
                'title'   => $title,
                'url'     => $url,
                'image'   => $image
            ];
            //增加积分
            ScoreLog::saveLog('collection',$this->auth->id,$aid);

            $model->setInc('collection', 1);

            CollectionModel::create($data);
            Db::commit();
        } catch (\think\Exception $e) {
            Db::rollback();
            $this->error('Operational errors');
        }
        $this->success("Collected successfully");
    }


    /**
     * 删除收藏
     */
    public function delete()
    {
        $id = (int)$this->request->post('id/d');
        if (!$id) {
            $this->error("参数不正确");
        }
        $collection = \addons\cms\model\Collection::where('id', $id)->where('user_id', $this->auth->id)->find();
        if (!$collection) {
            $this->error("未找到指定的收藏");
        }
        Db::startTrans();
        try {
            $collection->delete();
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error("移除收藏失败");
        }
        $this->success("移除收藏成功");
    }
}
